package server;

import org.apache.commons.lang3.text.StrSubstitutor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class StaticResourceProcessor {

    private static final int BUFFER_SIZE = 1024;
    // 下面的字符串是当文件没有找到时返回的404错误描述
    private static String fileNotFoundMessage = "HTTP/1.1 404 File Not Found\r\n" +
            "Content-Type: text/html\r\n" +
            "Content-Length: 23\r\n" + "\r\n" +
            "File Not Found";
    // 下面的字符串是正常情况下返回的，根据http协议，里面包含了相应的变量。
    private static String OKMessage = "HTTP/1.1 ${StatusCode} ${StatusName}\r\n"
            + "Content-Type: ${ContentType}\r\n"
            + "Content-Length: ${ContentLength}\r\n"
            + "Server: minit\r\n" +
            "Date: ${ZonedDateTime}\r\n" +
            "\r\n";
    // 处理过程很简单，先将响应头写入输出流，然后从文件中读取内容写入输出流

    public void process(HttpRequest request, HttpResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        String uri = request.getRequestURI();
        String webRoot = HttpSever.WEB_ROOT + uri;
        File file = new File(webRoot);
        if (file.exists()) {
            response.sendHeaders();
            // response.getWriter().println(composeResponseHead(file));

            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                byte[] buffer = new byte[BUFFER_SIZE];
                int len = 0;
                while ((len = fileInputStream.read(buffer)) != -1) {
                    response.getOutput().write(buffer, 0, len);
                }
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }

        } else {
            response.getOutput().write(fileNotFoundMessage.getBytes("utf-8"));

        }
    }

    // 拼响应头，填充变量值
    private String composeResponseHead(File file) {
        long fileLength = file.length();
        Map<String, Object> valuesMap = new HashMap<>();
        valuesMap.put("StatusCode", "200");
        valuesMap.put("StatusName", "OK");
        valuesMap.put("ContentType", "text/html;charset=utf-8");
        valuesMap.put("ContentLength", fileLength);
        valuesMap.put("ZonedDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ZonedDateTime.now()));
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        String responseHead = sub.replace(OKMessage);
        return responseHead;
    }
}